package dao;

import entry.Books;
import util.DBHelper;

import java.util.ArrayList;

public class BookDaoImpl implements BookDao {
    DBHelper dbHelper = new DBHelper();

    @Override
    public int insertBook(Books book) {
        String sql = "insert into books (bookname, bookauthor, bookpublish, bookpage, bookprice, createdate) values(?, ?, ?, ?, ?, ?)";
        return dbHelper.changeInfo(sql, book.getBookName(), book.getBookAuthor(), book.getBookPublish(), book.getBookPage(), book.getBookPrice(), book.getCreateDate());
    }

    @Override
    public ArrayList<Books> selectAll() {
        String sql = "select * from books";
        System.out.println(sql);
        return dbHelper.selectInfo(sql, Books.class);
    }

    @Override
    public ArrayList<Books> selectMatch(Books book) {
        ArrayList list = new ArrayList();
        StringBuilder str = new StringBuilder("select * from books where 1=1 ");
        if (book.getBookName() != null) {
            str.append("and BookName like ? ");
            return dbHelper.selectInfo(str.toString(),Books.class,"%"+book.getBookName()+"%");

        }
        if (book.getBookAuthor() != null) {
            str.append("and BookAuthor like ? ");
            return dbHelper.selectInfo(str.toString(),Books.class,"%"+book.getBookAuthor()+"%");
        }
        if (book.getBookPublish() != null) {
            str.append("and BookPublish like ? ");
            return dbHelper.selectInfo(str.toString(),Books.class,"%"+book.getBookAuthor()+"%");
        }else {
            return dbHelper.selectInfo(str.toString(),Books.class);
        }

        //return dbHelper.selectInfo(str.toString(),book.getClass(),list.toArray());
    }

    @Override
    public boolean deleteBook(int bid) {
        String sql="delete from books where bookid=? ";

        return dbHelper.changeInfo(sql,bid)>0?true:false;
    }

    @Override
    public Books selectById(int bid) {
        String sql="select * from books where bookid=? ";

        Books book = (Books) (dbHelper.selectInfo(sql, Books.class,bid).get(0));

        return book;
    }

    @Override
    public boolean updateBook(Books book) {
        String sql="update books set bookname=?,bookauthor=?,bookpublish=?,bookpage=?,bookprice=?,createdate=? where bookid=? ";
        Object[] objs={book.getBookName(),book.getBookAuthor(),book.getBookPublish(),book.getBookPage(),book.getBookPrice(),book.getCreateDate(),book.getBookId()};
        return dbHelper.changeInfo(sql,objs)>0?true:false;
    }
}

